package com.efast.dmom.mgmt.service.mes.barcode.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.redis.ObjectRedisTemplate;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.dmom.mgmt.bean.mes.barcode.BarCodeRuleBean;
import com.efast.dmom.mgmt.bean.mes.barcode.BarCodeRuleItemBean;
import com.efast.dmom.mgmt.bean.mes.barcode.ConfiguredBarCodeRuleBean;
import com.efast.dmom.mgmt.dao.mes.barcode.BarCodeRuleDao;
import com.efast.dmom.mgmt.service.mes.barcode.BarCodeRuleService;

@Service
public class BarCodeRuleServiceImpl implements BarCodeRuleService {

	@Autowired
	private ObjectRedisTemplate objectRedisTemplate;

	@Autowired
	private BarCodeRuleDao barcodeRuleDao;

	@Override
	public List<BarCodeRuleBean> getAllBarCodeRules() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public ResultBean refreshCache(int pConfigId) {
		
		ResultBean resultBean = new ResultBean(true, null);
		
		List<ConfiguredBarCodeRuleBean> configuredRuleBeanList = barcodeRuleDao.getBarCodeRuleByConfigId(pConfigId);
		String redisKey = this.getClass() + String.valueOf(pConfigId);
		objectRedisTemplate.opsForValue().set(redisKey, configuredRuleBeanList, 1800, TimeUnit.SECONDS);
		
		return resultBean;
	}

	@Override
	public ResultBean validateBarCode(int pConfigId, String barcode) {

		ResultBean resultBean = new ResultBean(true, null);

		if (barcode == null || "".equals(barcode)) {
			resultBean.setMessage("请扫描条码");
			resultBean.setSuccess(false);
			return resultBean;
		}
		
		String redisKey = this.getClass() + String.valueOf(pConfigId);

		@SuppressWarnings("unchecked")
		List<ConfiguredBarCodeRuleBean> configuredRuleBeanList = (List<ConfiguredBarCodeRuleBean>) objectRedisTemplate
				.opsForValue().get(redisKey);

		if (configuredRuleBeanList == null || configuredRuleBeanList.size() == 0) {

			configuredRuleBeanList = barcodeRuleDao.getBarCodeRuleByConfigId(pConfigId);

			if (configuredRuleBeanList == null || configuredRuleBeanList.size() == 0) {
				// TODO
//				resultBean.setMessage("此工位没有配置对应的条码规则");
//				resultBean.setSuccess(false);
				return resultBean;
			}
			objectRedisTemplate.opsForValue().set(redisKey, configuredRuleBeanList, 1800, TimeUnit.SECONDS);
		}

		String partNoVersion = null ;
		
		for (int i = 0; i < configuredRuleBeanList.size(); i++) {

			ConfiguredBarCodeRuleBean ruleBean = configuredRuleBeanList.get(i);
			List<BarCodeRuleItemBean> ruleItemBeanList = ruleBean.getRuleItems();
			
			partNoVersion = ruleBean.getPartNoVersion();

			boolean oneRuleMatch = true;
			int matchCounter = 0;
			for (int j = 0; j < ruleItemBeanList.size(); j++) {

				oneRuleMatch = true;
				BarCodeRuleItemBean ruleItemBean = ruleItemBeanList.get(j);

				String startPattern = ruleItemBean.getStartPattern();
				String endPattern = ruleItemBean.getEndPattern();
				int length = ruleItemBean.getBarcodeLength();

				if ((length != 0 && length != barcode.length())
						|| (startPattern != null && ! barcode.startsWith(startPattern))
						|| (endPattern != null && ! barcode.endsWith(endPattern))) {
					oneRuleMatch = false;
					break;
				}
				matchCounter++;
			}
			if (oneRuleMatch && matchCounter == ruleItemBeanList.size()) {
				resultBean.setObject(ruleBean.getPartNoVersion());
				resultBean.setSuccess(true);
				return resultBean;
			}
		}
		resultBean.setMessage("输入的条码【" + barcode + "】与此工位配置的零件【" + (partNoVersion == null ? "" : partNoVersion) + "】条码规则不匹配");
		resultBean.setSuccess(false);
		
		return resultBean;
	}

	//
	@Override
	public ResultBean updateBarcodeRule(BarCodeRuleBean barCodeRuleBean) {
	   ResultBean resultBean = new ResultBean(true,"'");
	   if(barCodeRuleBean != null) {
		  barCodeRuleBean.setLastUpdateTime(new Date());;
	      barCodeRuleBean.setLastUpdateUser(SpringWebUtils.getRequestUser());
	      Boolean flag=barcodeRuleDao.updateBarcodeRule(barCodeRuleBean);
	     if(flag) {
	      barcodeRuleDao.updateTrBasProductCfgBi(barCodeRuleBean);
          List<Integer> productConfigIdList = barcodeRuleDao.getProductConfigId(barCodeRuleBean.getRuleId());
          if(productConfigIdList != null && productConfigIdList.size()>0) {
    	     for(Integer productConfigId : productConfigIdList) {
    		      this.refreshCache(productConfigId);
    	     }
           }
           resultBean.setSuccess(true);
	       resultBean.setMessage("更新成功！");
	     } else {
	       resultBean.setSuccess(true);
      	   resultBean.setMessage("更新失败！"); 
	     }
	   }
	       return resultBean;
	}

	@Override
	public ResultBean updateBarcodeRuleItem(BarCodeRuleItemBean barCodeRuleItemBean) {
		ResultBean resultBean = new ResultBean(true,"'");
        if(barCodeRuleItemBean != null) {
    	   barCodeRuleItemBean.setLastUpdateTime(new Date()); 
    	   barCodeRuleItemBean.setLastUpdateUser(SpringWebUtils.getRequestUser());
    	   Boolean flag = barcodeRuleDao.updateBarcodeRuleItem(barCodeRuleItemBean);
    	   if (flag) {
    	   List<Integer> productConfigIdList = barcodeRuleDao.getProductConfigId(barCodeRuleItemBean.getRuleId());   
    	   if(productConfigIdList != null && productConfigIdList.size()>0) {
    		   for(Integer productConfigId : productConfigIdList) {
    			   this.refreshCache(productConfigId); 
    		   }
    	   }
    	       resultBean.setSuccess(true);
    	       resultBean.setMessage("更新成功！");
    	   } else {
    		   resultBean.setSuccess(true);
        	   resultBean.setMessage("更新失败！");   
    	   }
       }
		return resultBean;		
	}

}
